﻿//--------------------------------------------------------------------------
// 
//  Copyright (c) Chili Software.  All rights reserved. 
// 
//  File: VistaDBStorage.cs
//
//  Description: Provides a storage class for VistaDB 3.x.
// 
//--------------------------------------------------------------------------

using System;
using System.Reflection;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using VistaDB.Provider;
using Chili.Opf3.Query;
using VistaDB.Diagnostic;
using Chili.Opf3.Query.OPathParser;

namespace Chili.Opf3.Storages.VistaDB3
{
	/// <summary>Storage class that encapsulates a pyhsical VistaDB 3.x database.</summary>
	/// <remarks>
	/// 	<para>This class encapsulates a physical VistaDB database. It is used to access to
	///     an VistaDB database that is installed somewhere on your or on a remote machine. The storage
	///     implements the basic interfaces, such as
	///     <see cref="Opf3.Storages.IStorage">IStorage</see> for the basic storage IO
	///     functinality and
	///     <see cref="Opf3.Storages.ITransactionStorage">ITransactionStorage</see> for the
	///     transaction management.</para>
	/// 	<para><b>Attention:</b> You should not access the methods of the storage directly
	///     but instead register the storage with your instances of the
	///     <see cref="Opf3.ObjectContext">ObjectContext</see>. The
	///     <see cref="Opf3.ObjectContext">ObjectContext</see> accesses the methods internally
	///     to get the objects from the storage.</para>
	/// </remarks>
	/// <example>
	///     The following example shows how you should use the VistaDB storage in your
	///     applications. 
	///     <code lang="CS">
	/// // ... Other code
	///  
	/// // Creates a new ObjectContext that uses a VistaDB database as storage.
	/// // You should only pass an instance of the storage to your ObjectContext.
	/// // That's it! Nothing more. The methods of the storage are accessed
	/// // by the context internally.
	/// ObjectContext context = new ObjectContext(
	///     new VistaDBStorage("... some ConnectionString ..."));
	///  
	/// // ... Other code
	///     </code>
	/// </example>
	public class VistaDBStorage : SqlStorageBase
	{
		/// <summary>
		/// Creates a new instance of the <see cref="VistaDBStorage">VistaDBStorage Class</see>.
		/// </summary>
		/// <param name="connectionString">Specifies a string that contains the information (for ADO.NET) to connect to storage.</param>
		/// <exception cref="ArgumentNullException">ConnectionString is null.</exception>
		public VistaDBStorage(string connectionString) : base(connectionString)
		{
			base.StorageCommandBuilders.Add(new VistaDBCommandBuilder());
			base.StorageCommandBuilders.Add(new SqlQueryCommandBuilder());
		}

		/// <summary>
		/// Creates a new instance of the <see cref="VistaDBStorage">VistaDBStorage
		/// Class</see>.
		/// </summary>
		/// <param name="path">Specifies the path of the database.</param>
		/// <param name="fileName">Specifies the file name of the database.</param>
		/// <exception cref="ArgumentNullException">FileName is null.</exception>
		/// <exception cref="ArgumentNullException">Path is null.</exception>
		public VistaDBStorage(string path, string fileName) 
			: this(string.Format(@"Data Source={0}\{1}", path, fileName))
		{
			if (path == null)
				throw new ArgumentNullException("path");
			if (fileName == null)
				throw new ArgumentNullException("fileName");
		}

		#region Overridden Members

		/// <summary>
		/// Executes a command on the storage that does not expect any results. It the method
		/// returns an argument it is used by the framework to set the
		/// <see cref="Opf3.FieldAttribute.AutoNumber">AutoNumber</see> property of the persistent
		/// object.
		/// </summary>
		/// <param name="query">
		/// 	<see cref="Opf3.Query.IQuery">IQuery</see> that is compiled and executed on the
		/// storage.
		/// </param>
		/// <exception cref="Opf3.Storages.StorageConstraintException">A constraint of the storage 
		/// has been violated.</exception>
		/// <exception cref="Opf3.Storages.ForeignKeyViolationException">A foreign key in the storage 
		/// has been violated.</exception>
		/// <exception cref="Opf3.Storages.PrimaryKeyViolationException">A duplicate primary key 
		/// is inserted in the storage.</exception>
		/// <exception cref="Opf3.Storages.PrimaryKeyViolationException">An index has been violated.</exception>
		/// <exception cref="Opf3.Storages.StorageException">Any other unexpected storage exception.</exception>
		public override object ExecuteCommand(IQuery query)
		{
			try
			{
				object autoValue = null;

				CompiledQuery compiledQuery = query.ToCompiledQuery(this);
				Tracing.Current.TraceStorageIO(compiledQuery);

				// Prepare the command for execution.
				using (IDbCommand dbCommand = this.PrepareCommand(compiledQuery))
				{
					dbCommand.ExecuteNonQuery();

					if (query.QueryType == QueryTypes.Insert)
					{
						// Check if the query's parameter contain an autonumber parameter.
						if (compiledQuery.AutoNumberItems != null)
						{
							foreach (AutoNumberItem item in compiledQuery.AutoNumberItems)
							{
								string sql = @"SELECT LastIdentity(" + item.FieldAttribute.FieldName + ") FROM " + compiledQuery.AutoNumberItems.PersistentAttribute.Entity;
								VistaDBCommand idCommand = new VistaDBCommand(sql, (VistaDBConnection)dbCommand.Connection);
								idCommand.Transaction = (VistaDBTransaction)dbCommand.Transaction;

								// Convert the return value to a long.
								autoValue = idCommand.ExecuteScalar();
								Tracing.Current.TraceStorageIO("Autonumber value returned: " + autoValue);
							}
						}
					}

					// If no transaction is active we can close the connection after executing the command.
					if (!IsTransactionActive)
						dbCommand.Connection.Close();
				}
				return autoValue;
			}
			catch (VistaDBException ex)
			{
				throw new StorageException(ex.Message, ex, query);
			}
		}

		/// <summary>
		/// Executes and compiles the <see cref="Opf3.Query.IQuery">IQuery</see> and returns
		/// an <see cref="Opf3.ObjectReader{T}">ObjectReader</see> with the resultsset.
		/// </summary>
		/// <param name="context">
		/// 	<see cref="Opf3.ObjectContext">ObjectContext</see> that is connected with the
		/// <see cref="Opf3.ObjectReader{T}">ObjectReader</see>.
		/// </param>
		/// <param name="query">
		/// 	<see cref="Opf3.Query.IQuery">IQuery</see> that is compiled and executed on the
		/// storage.
		/// </param>
		/// <exception cref="Opf3.Storages.StorageException">An unexpected storage exception has happened.</exception>
		public override ObjectReader<T> ExecuteReader<T>(ObjectContext context, IQuery query)
		{
			try
			{
				return base.ExecuteReader<T>(context, query);
			}
			catch (VistaDBException ex)
			{
				throw new StorageException(ex.Message, ex, query);
			}
		}

		/// <summary>
		/// Starts a new transaction.
		/// </summary>
		/// <returns>Returns an instance of the <see cref="Transaction">Transaction</see> object.</returns>
		public override Transaction StartTransaction()
		{
			return StartTransaction(IsolationLevel.Snapshot);
		}

		/// <summary>
		/// Creates a new transaction. Transaction level is not allowed by this storage.
		/// Use StartTransaction without arguments instead.
		/// </summary>
		/// <param name="level"><see cref="System.Data.IsolationLevel">IsolationLevel</see> of the transaction.</param>
		/// <param name="connection">The connection that is used to start the transaction.</param>
		/// <returns>Returns an instance of the <see cref="SqlTransactionBase">SqlTransactionBase</see> object.</returns>
		/// <exception cref="NotSupportedException">Method is not supported by the storage.</exception>
		protected override SqlTransactionBase CreateTransaction(IsolationLevel level, IDbConnection connection)
		{
			if (level != IsolationLevel.ReadCommitted)
			{
				// IsolationLevel is not supported.
				throw new NotSupportedException("VistaDB supports only the ReadCommitted isolation level.");
			}
			return base.CreateTransaction(level, connection);
		}

		/// <summary>Creates a new storage dependent connection object.</summary>
		/// <returns>Returns an instance of a storage dependent connection object.</returns>
		public override IDbConnection CreateConnection()
		{
			VistaDBConnection connection = new VistaDBConnection(this.ConnectionString);
			connection.Open();
			return connection;
		}

		/// <summary>Creates a new storage dependent command object.</summary>
		/// <returns>Returns an instance of a storage dependent command object.</returns>
		public override IDbCommand CreateCommand()
		{
			return new VistaDBCommand();
		}

		/// <summary>Creates and populates a storage dependent parameter with data.</summary>
		/// <returns>
		/// The name of the storage parameter should be set to a valid parameter name (one
		/// that is supported by the storage) while creating the parameter.
		/// </returns>
		/// <param name="index">Index of the storage parameter.</param>
		/// <param name="name">Name of the storage parameter.</param>
		/// <param name="value">Value of the storage parameter.</param>
		/// <param name="type">The type of the value argument. This information is useful if the value is null.</param>
		/// <exception cref="ArgumentNullException">Name is null.</exception>
		public override IDataParameter CreateParameter(int index, ref string name, object value, Type type)
		{
			if (name == null)
				throw new ArgumentNullException("name", "Name is null.");

			// Set the name for the parameter.
			name = "@" + name;

			return new VistaDBParameter(name, value == null ? DBNull.Value : value);
		}

		/// <summary>Transforms the parameter to a valid field.</summary>
		/// <returns>Returns a string that represents a valid field name.</returns>
		/// <remarks>
		/// This method returns a field name that is valid for the current storage. For some
		/// storages it is a better choice to start each field name with a '[' and end with a ']'
		/// (Ms Access) - This method could wrap each field name passed with '[]'.
		/// </remarks>
		/// <param name="name">Name for the field that is transformed.</param>
		/// <exception cref="ArgumentNullException">Name is null.</exception>
		public override string GetValidFieldName(string name)
		{
			if (name == null)
				throw new ArgumentNullException("name", "Name is null.");

			return string.Format("[{0}]", name);
		}

		/// <summary>
		/// Transforms the name of the entity to a valid entity name.
		/// </summary>
		/// <returns>Returns a string that represents a valid entity name.</returns>
		/// <remarks>
		/// This method returns an entity name that is valid for the current storage. For
		/// some storages it is a better choice to start each entity name with a '[' and end with a
		/// ']' (Ms Access) - This method could wrap each entity name passed with '[]'.
		/// </remarks>
		/// <param name="name">Name of the entity.</param>
		/// <exception cref="ArgumentNullException">Name is null.</exception>
		public override string GetValidEntityName(string name)
		{
			if (name == null)
				throw new ArgumentNullException("name", "Name is null.");

			return name;
		}

		#endregion
	}
}
